import { getSetting,chooseAddress,openSetting,showModal,showToast,requestPayment } from "../../utils/asyncWx.js";
import { request } from "../../request/index.js";
Page({
  data: {
    address:{},
    cart:[],
    totalPrice:0,
    totalNum:0
  },
  onShow(){
    //获取缓存中的收货地址
    let address=wx.getStorageSync("address");
    //获取购物车数据
    let cart=wx.getStorageSync("cart");
    //获取过滤后的购物车数组
    cart=cart.filter(v=>v.checked);
    //总价格 总数量
    let totalNum=0;
    let totalPrice=0;
    //给数组做循环
    cart.forEach(v=>{
        totalPrice+=v.num*v.goods_price;
        totalNum+=v.num;
    });
    //给data赋值
    this.setData({
      cart,
      totalPrice,
      totalNum,
      address
    });
  },
  //点击支付事件-token=令牌
  async handleOrderPay(){
   try {
      //1 获取缓存中的用户token
    const token=wx.getStorageSync("token");
    //2 判断是否有数据
    if(!token){
      wx.navigateTo({
        url: '/pages/auth/auth',
      });
      return;
    }
    //3 创建订单
    //3.1 准备请求头参数
    //const header={Authorization:token};
    //3.2 准备请求体参数
    const order_price=this.data.totalPrice;//价格
    const consignee_addr=this.data.address.all;//地址
    let goods=[];//订单数组
    let {cart}=this.data;
    cart.forEach(v=>goods.push({
      goods_id:v.goods_id,
      goods_number:v.num,
      goods_price:v.goods_price
    }))
    const orderParams={order_price,consignee_addr,goods};
    //4 准备发送请求 创建订单，获取订单编号
    //const res=await request({url:"my/orders/req_unifiedorder",method:"POST",data:orderParams});
    const result={
      order_number:"123abc54545",
      order_price:order_price,
      consignee_addr:consignee_addr
    }
    const {order_number}=result;//获取订单编号
    //5 发起预支付
    //const res=await request({url:"/my/orders/req_unifiedorder",method:"POST",data:{order_number}});
    const res={
      pay:{
        timeStamp: '123',
        nonceStr: '321',
        package: '1234567',
       signType: 'sb',
       paySign: 'dms'
      }
    }
    //将pay解构出来
    const {pay}=res;
    //6 发起微信支付
    //const ress=await requestPayment(pay);--不能搞了，没有正确的属性会报错了
    await showToast({title:"假装支付成功~"});
    //7查询后台 查看订单状态
    //const ress=await request({url:"/my/orders/create",method:"POST",data:{order_number}});
    const ress="支付成功";//假装支付成功，根据后台查询得到的
    //9 手动删除缓存中的数据
    let newCart=wx.getStorageSync("cart");
    newCart=newCart.filter(v=>!v.checked);//获取未被选中的商品
    wx.setStorageSync("cart",newCart);
    //8 支付成功 跳转到订单页面
    wx.navigateTo({
      url: '/pages/order/order',
    });
   } catch (error) {
     await showToast("支付失败");
     console.log(error);
   }
  }
});
